/**
 * swiper.init.js
 */
var comtainer = document.getElementById('swiper_container');
if (comtainer) {
  var swiper = new Swiper('.blog-slider', {
    passiveListeners: true,
    spaceBetween: 30,
    effect: 'fade',
    loop: true,
    autoplay: {
      disableOnInteraction: true,
      delay: 3000
    },
    mousewheel: false,
    // autoHeight: true,
    pagination: {
      el: '.blog-slider__pagination',
      clickable: true,
    }
  });
  comtainer.onmouseenter = function () {
    swiper.autoplay.stop();
  };
  comtainer.onmouseleave = function () {
    swiper.autoplay.start();
  }
}

/**
 * friendcircle.js
 */
requests_url = 'https://friends.allapi.cc/api';
if (document.getElementById('friend_link_circle')) {
  const friend_link_circle = new Vue({
    el: '#friend_link_circle',
    data: {
      datalist: [],
      datalist_slice: [],
      maxnumber: 20,
      addnumber: 10,
      display: true,
      loadmore_display: false,
      listlenth: 0,
      today_post: 0,
      last_update_time: '',
      user_lenth: '',
      error: 0,
      unique_live_link: 0,
      opentype: '_blank'  //'_blank'打开新标签,'_self'本窗口打开

    },
    methods: {
      unique(arr) {
        return Array.from(new Set(arr))
      },
      formatDate(strDate) {
        try {
          let date = new Date(Date.parse(strDate.replace(/-/g, "/")));
          let gettimeoffset = 0
          if (new Date().getTimezoneOffset()) {
            gettimeoffset = new Date().getTimezoneOffset();
          }
          else {
            gettimeoffset = 8;
          }
          let timeoffset = gettimeoffset * 60 * 1000;
          let len = date.getTime();
          let date2 = new Date(len - timeoffset);
          let sec = date2.getSeconds().toString();
          let min = date2.getMinutes().toString();
          if (sec.length === 1) {
            sec = "0" + sec;
          }
          if (min.length === 1) {
            min = "0" + min;
          }
          return date2.getFullYear().toString() + "/" + (date2.getMonth() + 1).toString() + "/" + date2.getDate().toString() + " " + date2.getHours().toString() + ":" + min + ":" + sec
        } catch (e) { return "" }
      },
      timezoon() {
        try{
          let time = this.datalist_slice[0][1][0][5];
          return this.formatDate(time)
        }catch(e){
          console.warn(`timezoon Error:`,{e})
        }
      },
      todaypost() {
        let date = new Date();
        let year = date.getFullYear();
        let month = (date.getMonth() + 1).toString();
        let day = (date.getDate()).toString();
        if (month.length === 1) {
          month = "0" + month;
        }
        if (day.length === 1) {
          day = "0" + day;
        }
        return year + "-" + month + "-" + day
      },
      addmaxnumber() {
        this.maxnumber = this.maxnumber + this.addnumber;
        if (this.maxnumber >= this.listlenth) {
          this.loadmore_display = false;
        }
      },
      slice(data) {
        let monthlist = [];
        let datalist = [];
        let data_slice = data;
        for (let item in data_slice) {
          data_slice[item].push(item);
          if (data_slice[item][1].lenth !== 10) {
            let list = data_slice[item][1].split('-')
            if (list[1].length < 2) {
              list[1] = "0" + list[1]
            }
            if (list[2].length < 2) {
              list[2] = "0" + list[2]
            }
            data_slice[item][1] = list.join('-')
          }
          let month = data_slice[item][1].slice(0, 7);
          if (monthlist.indexOf(month) !== -1) {
            console.log(month);
            datalist[monthlist.length - 1][1].push(data_slice[item]);
          }
          else {
            monthlist.push(month);
            datalist.push([month, [data_slice[item]]]);
          }
        }

        for (let mounthgroup of datalist) {
          mounthgroup.push(mounthgroup[1][0][6]);
        }
        console.log(datalist);
        return datalist
      }
    },
    mounted: function () {

      fetch(requests_url).then(
        data => data.json()
      ).then(
        data => {
          let today = this.todaypost();
          let Datetody = new Date(today);
          for (let item = 0; item < data[1].length; item++) {
            let Datedate = new Date(data[1][item][1])
            if (Datedate > Datetody) {
              data[1].splice(item--, 1);
              console.log('穿越了');
            }
          }
          this.datalist = data[1];
          this.listlenth = data[1].length;
          this.user_lenth = data[0].length;
          this.datalist_slice = this.slice(data[1]);
          this.last_update_time = this.timezoon();
          this.loadmore_display = true;
          let link_list = [];
          for (let item of data[1]) {
            if (item[1] === today) {
              this.today_post += 1;
            }
            link_list.push(item[3]);
          }
          let arr = this.unique(link_list);
          this.unique_live_link = arr.length;
          for (let item of data[0]) {
            if (item[3] === 'true') {
              this.error += 1;
            }
          }
        }
      )
    }
  })
}
/**
 * 说说初始化
 */
typeof Artitalk !== "undefined" && new Artitalk({
  serverURL: "https://talk.cxvh.com",
  appId: 'vtjJa3dR6y3CAQDTTv9C8SaK-gzGzoHsz', // Your LeanCloud appId
  appKey: 'CDp4qQ242izArr7xaDh46e5o' // Your LeanCloud appKey
})

/**
 * gitcalendar.js
 */
 var gitcalendar = new Vue({
  el: '#gitcalendar',
  data: {
    simplemode: true,
    user: 'cxvh',
    fixed: 'fixed',
    px: 'px',
    x: '',
    y: '',
    span1: '',
    span2: '',
    month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthchange: [],
    oneyearbeforeday: '',
    thisday: '',
    amonthago: '',
    aweekago: '',
    weekdatacore: 0,
    datacore: 0,
    total: 0,
    datadate: '',
    data: [],
    positionplusdata: [],
    firstweek: [],
    lastweek: [],
    beforeweek: [],
    thisweekdatacore: 0,
    mounthbeforeday: 0,
    mounthfirstindex: 0,
    crispedges: 'crispedges',
    thisdayindex: 0,
    amonthagoindex: 0,
    amonthagoweek: [],
    firstdate: [],
    first2date: [],
    montharrbefore: [],
    monthindex: 0,
    // color: ['#ebedf0', '#f1f8ff', '#dbedff', '#c8e1ff', '#79b8ff', '#2188ff', '#0366d6', '#005cc5', '#044289', '#032f62', '#05264c']
    color: ["#e4dfd7", "#f9f4dc", "#f7e8aa", "#f7e8aa", "#f8df72", "#fcd217", "#fcc515", "#f28e16", "#fb8b05", "#d85916", "#f43e06"]
  },
  methods: {
    selectStyle(data, event) {
      document.querySelector('.angle-wrapper').style.display = 'block'
      this.span1 = data.date;
      this.span2 = data.count;
      this.x = event.clientX - 100;
      this.y = event.clientY - 60
    },
    outStyle() {
      document.querySelector('.angle-wrapper').style.display = 'none'
    },
    thiscolor(x) {
      if (x === 0) {
        let i = parseInt(x / 2);
        return this.color[0]
      } else if (x < 2) {
        return this.color[1]
      } else if (x < 20) {
        let i = parseInt(x / 2);
        return this.color[i]
      } else {
        return this.color[9]
      }
    },
  }
});
var apiurl = 'https://githubapi.ryanchristian.dev/user/'
var githubapiurl = apiurl + gitcalendar.user;
//canvas繪圖
function responsiveChart() {
  let c = document.getElementById("gitcanvas");
  if (c) {
    let cmessage = document.getElementById("gitmessage");
    let ctx = c.getContext("2d");
    c.width = document.getElementById("gitcalendarcanvasbox").offsetWidth;
    let linemaxwitdh = 0.96 * c.width / gitcalendar.data.length;
    c.height = 9 * linemaxwitdh;
    let lineminwitdh = 0.8 * linemaxwitdh;
    let setposition = {
      x: 0.02 * c.width,
      y: 0.025 * c.width
    };
    for (let week in gitcalendar.data) {
      weekdata = gitcalendar.data[week];
      for (let day in weekdata) {
        let dataitem = {
          date: "",
          count: "",
          x: 0,
          y: 0
        };
        gitcalendar.positionplusdata.push(dataitem);
        ctx.fillStyle = gitcalendar.thiscolor(weekdata[day].count);
        setposition.y = Math.round(setposition.y * 100) / 100;
        dataitem.date = weekdata[day].date;
        dataitem.count = weekdata[day].count;
        dataitem.x = setposition.x;
        dataitem.y = setposition.y;
        ctx.fillRect(setposition.x, setposition.y, lineminwitdh, lineminwitdh);
        setposition.y = setposition.y + linemaxwitdh
      };
      setposition.y = 0.025 * c.width;
      setposition.x = setposition.x + linemaxwitdh
    };
    ctx.font = "600  Arial";
    ctx.fillStyle = '#aaa';
    ctx.fillText("日", 0, 1.9 * linemaxwitdh);
    ctx.fillText("二", 0, 3.9 * linemaxwitdh);
    ctx.fillText("四", 0, 5.9 * linemaxwitdh);
    ctx.fillText("六", 0, 7.9 * linemaxwitdh);
    let monthindexlist = c.width / 24;
    for (let index in gitcalendar.monthchange) {
      ctx.fillText(gitcalendar.monthchange[index], monthindexlist, 0.7 * linemaxwitdh);
      monthindexlist = monthindexlist + c.width / 12
    };
    cmessage.onmousemove = function (event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
    };
    c.onmousemove = function (event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
      getMousePos(c, event);
    };

    function getMousePos(canvas, event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left * (canvas.width / rect.width);
      var y = event.clientY - rect.top * (canvas.height / rect.height);
      //console.log("x:"+x+",y:"+y);
      for (let item of gitcalendar.positionplusdata) {
        let lenthx = x - item.x;
        let lenthy = y - item.y;
        //console.log(lenthx,lenthy);
        if (0 < lenthx && lenthx < lineminwitdh) {
          if (0 < lenthy && lenthy < lineminwitdh) {
            //console.log(item.date,item.count)
            document.querySelector('.angle-wrapper').style.display = 'block'
            gitcalendar.span1 = item.date;
            gitcalendar.span2 = item.count;
            gitcalendar.x = event.clientX - 100;
            gitcalendar.y = event.clientY - 60
          }
        }
        //if(0< x - item.x <lineminwitdh&&0< y - item.y <lineminwitdh){
        //console.log(item.count,item.date);
        //}
      }
    }
  }
}
//數據統計算法
function addlastmonth() {
  if (gitcalendar.thisdayindex === 0) {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweekcore(48);
    gitcalendar.thisweekdatacore += gitcalendar.firstdate[6].count;
    gitcalendar.amonthago = gitcalendar.firstdate[6].date
  } else {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweek2core();
    gitcalendar.amonthago = gitcalendar.first2date[gitcalendar.thisdayindex - 1].date
  }
};

function thisweek2core() {
  for (let i = gitcalendar.thisdayindex - 1; i < gitcalendar.first2date.length; i++) {
    gitcalendar.thisweekdatacore += gitcalendar.first2date[i].count
  }
};

function thisweekcore(index) {
  for (let item of gitcalendar.data[index]) {
    gitcalendar.thisweekdatacore += item.count
  }
};

function addlastweek() {
  for (let item of gitcalendar.lastweek) {
    gitcalendar.weekdatacore += item.count
  }
};

function addbeforeweek() {
  for (let i = gitcalendar.thisdayindex; i < gitcalendar.beforeweek.length; i++) {
    gitcalendar.weekdatacore += gitcalendar.beforeweek[i].count
  }
};

function addweek(data) {
  if (gitcalendar.thisdayindex === 6) {
    gitcalendar.aweekago = gitcalendar.lastweek[0].date;
    addlastweek()
  } else {
    lastweek = data.contributions[51];
    gitcalendar.aweekago = lastweek[gitcalendar.thisdayindex + 1].date;
    addlastweek();
    addbeforeweek()
  }
}

fetch(githubapiurl)
  .then(data => data.json())
  .then(data => {
    gitcalendar.data = data.contributions;
    gitcalendar.total = data.total;
    gitcalendar.first2date = gitcalendar.data[48];
    gitcalendar.firstdate = gitcalendar.data[47];
    gitcalendar.firstweek = data.contributions[0];
    gitcalendar.lastweek = data.contributions[52];
    gitcalendar.beforeweek = data.contributions[51];
    gitcalendar.thisdayindex = gitcalendar.lastweek.length - 1;
    gitcalendar.thisday = gitcalendar.lastweek[gitcalendar.thisdayindex].date;
    gitcalendar.oneyearbeforeday = gitcalendar.firstweek[0].date;
    gitcalendar.monthindex = gitcalendar.thisday.substring(5, 7) * 1;
    gitcalendar.montharrbefore = gitcalendar.month.splice(gitcalendar.monthindex, 12 - gitcalendar.monthindex);
    gitcalendar.monthchange = gitcalendar.montharrbefore.concat(gitcalendar.month);
    addweek(data);
    addlastmonth();
    responsiveChart();
  })
  .catch(function (error) {
    console.log(error);
  });

//手機版更換為svg繪制
var gitcalendarcanvasbox=document.getElementById("gitcalendarcanvasbox")
if (gitcalendarcanvasbox&&gitcalendarcanvasbox.offsetWidth < 500) {
  gitcalendar.simplemode = false
}

//當改變窗口大小時重新繪制canvas
window.onresize = function () {
  if (gitcalendar.simplemode) responsiveChart()
}

//解決滾動滑輪時出現的標簽顯示
window.onscroll = function () {
  if (document.querySelector('.angle-wrapper')) {
    document.querySelector('.angle-wrapper').style.display = 'none'
  }
};